-- wounded_magic
-- created by zhuangsl
-- 收到伤害时使用魔法

return {
    apply = function(prop, baseValue)
        return prop[3];
    end,

    -- 每回合触发
    trigger = function(who, prop, arg)
        if who.type ~= OBJECT_TYPE_MONSTER then
            return false;
        end

        -- 如果无法行动
        if FormulaM.invoke("CAN_MONSTER_ACTIVE_ATTACK", who, prop) or
            FormulaM.invoke("MONSTER_IS_STOPED", who) then
            return false;
        end

        local target;
        local grid = DungeonM.getGridByPos(who:getPos());
        local skillId = prop[3];
        local skills = SkillM.getSkillTable();
        if not skills[skillId] then
            return false;
        end

        local dbase = SkillM.query(skillId, "dbase") or {};

        -- 目标
        if SkillM.needTarget(skillId) then
            target = ME.user;
        -- 召唤技能目标为自己
        elseif dbase["is_summon"] == 1 then
            target = who;
        else
            for p = 1, DUNGEON_WIDTH * DUNGEON_HEIGHT do
                grid = DungeonM.getGridByPos(p);

                -- 是未死亡的怪物
                if grid:isOpened() and
                    grid:isMonster() and
                    not grid.monster:isDead()then
                    target = grid.monster;
                    break;
                end
            end

            -- 已经没有目标了，不处理
            if not target then
                return false;
            end
        end

        local msg = string.format("%s受伤使用魔法： %d", who:query("name") or "", skillId);
        trace("remote_magic", msg);

        SkillM.apply(who, target, skillId, CombatM.getRound());

        return true;
    end,

    record = function(target, prop, path)
        return false;
    end
};
